package colopllet.colopl.pc.request;

import gae.util.http.client.Cookie;
import gae.util.http.client.Header;
import gae.util.http.client.HttpRequest;
import gae.util.http.client.HttpResponse;
import colopllet.colopl.pc.ColoplPCRequestException;
import colopllet.colopl.pc.response.AuthenticationResponse;
import colopllet.colopl.pc.session.ColoplSession;

public class AuthenticationRequest extends AbstractColoplRequest<AuthenticationResponse> {
    
    protected final static String PC_AUTH_URL = "http://colopl.jp/s/c/authentication/entrance";
    
    public AuthenticationRequest(ColoplSession session) {
        this.session = session;
    }
    
    @Override
    public HttpRequest createRequest() throws ColoplPCRequestException {
        HttpRequest req = new HttpRequest("GET", PC_AUTH_URL);
        Header reqHeader = getDefaultRequestHeader();
        Cookie reqCookie = new Cookie();
        reqCookie.addParam("pt", session.getPt(), 0);
        reqHeader.setCookie(reqCookie);
        req.setHeader(reqHeader);
        
        return req;
    }

    @Override
    public AuthenticationResponse parseResponse(HttpResponse res) throws ColoplPCRequestException {
        AuthenticationResponse result = new AuthenticationResponse();
        
        Header header = res.getHeader();
        Cookie cookie = header.getCookie();
        session.setJsessionid(cookie.getParam("JSESSIONID"));
        if (cookie.getParam("pt") != null) {
            session.setPt(cookie.getParam("pt"));
        }
        session.setCookieUsername(cookie.getParam("username"));
        result.setLocation(header.get("Location").get(0));
        
        return result;
    }

}
